﻿using PMIS.Common.Dialog;
using PMIS.Controls;
using PMIS.HttpRequest;
using PMIS.Shared.DTO;
using System.Windows.Input;

namespace PMIS.ViewModels.DataDict
{
    public class AddEditDataDictViewModel : DialogViewModelBase
    {
        private readonly HttpService _httpService;

        public AddEditDataDictViewModel(HttpService httpService)
        {
            _httpService = httpService;

            this.DataDict = new DataDictDto();
        }

        private DataDictDto _dataDict;

        public DataDictDto DataDict
        {
            get
            {
                return _dataDict;
            }
            set
            {
                SetProperty(ref _dataDict, value);
            }
        }

        private ICommand _saveCommand;
        public ICommand SaveCommand
        {
            get
            {
                if (_saveCommand == null)
                {
                    _saveCommand = new DelegateCommand(OnSave);
                }
                return _saveCommand;
            }
        }

        private ICommand _cancelCommand;
        public ICommand CancelCommand
        {
            get
            {
                if (_cancelCommand == null)
                {
                    _cancelCommand = new DelegateCommand(OnCancel);
                }
                return _cancelCommand;
            }
        }

        private async void OnSave()
        {
            bool result = false;
            if (this.DataDict.Id == null)
            {
                result = await Add();
            }
            else
            {
                result = await Edit();
            }

            if (result)
            {
                CloseDialog(new DialogResult(ButtonResult.OK));
            }
            else
            {
                ToastManager.ShowToast("保存失败");
            }
        }

        private async Task<bool> Add()
        {
            var response = await _httpService.PostAsync(Api.DATADICT_ADD, _dataDict);
            if (response?.code == 1)
            {
                long r = (long)response.data;
                return r == 1;
            }
            return false;
        }

        private async Task<bool> Edit()
        {
            var response = await _httpService.PutAsync(Api.DATADICT_UPDATE, _dataDict);
            if (response?.code == 1)
            {
                long r = (long)response.data;
                return r == 1;
            }
            return false;
        }

        private void OnCancel()
        {
            CloseDialog(new DialogResult(ButtonResult.Cancel));
        }

        public override void OnDialogOpened(IDialogParameters parameters)
        {
            if (parameters.Count > 0)
            {
                this.Title = "编辑数据字典";
                this.DataDict = parameters.GetValue<DataDictDto>("data");
            }
            else
            {
                this.Title = "新建数据字典";
            }
        }
    }
}
